<?php

namespace app\admin\dao;

use app\common\model\Keywords;
use app\common\model\KeywordsAnalysis;
use ShidianUtil\Thinkphp\Dao\DaoTrait;

/**
 * KeywordsAnalysisDao 数据访问对象
 * Class KeywordsAnalysisDao
 * @package app\admin\dao
 * @method KeywordsAnalysis findByPK(?int $id, $field = true)
 * @method \think\Collection selectAll(?int $page, ?int $page_size, $field = true)
 * @method KeywordsAnalysis insertActive(array $params, array $allow_field = [])
 * @method KeywordsAnalysis updateActive(KeywordsAnalysis $model, array $params, array $allow_field = [])
 * @method KeywordsAnalysis findAndUpdateActive(int $id, array $params, array $allow_field = [])
 * @method KeywordsAnalysis updateActiveByClosure(\Closure $closure, array $params, array $allow_field = [])
 * @method void deleteModel(KeywordsAnalysis $model)
 * @method void deleteById(int|array|\Closure $id, bool $force = false)
 * @link https://www.kancloud.cn/manual/thinkphp6_0/1037579
 * @link https://www.kancloud.cn/manual/think-orm/1257998
 * @link https://www.kancloud.cn/thinkphp/master-database-and-model/265551
 */
class KeywordsAnalysisDao
{
    use DaoTrait;

    /**
     * @var KeywordsAnalysis
     */
    private $baseModel;

    /**
     * KeywordsAnalysisDao constructor.
     */
    public function __construct()
    {
        $this->baseModel = KeywordsAnalysis::class;
    }

    public function listKeywords($time, $kw, ?int $page, ?int $page_size): array
    {
        $subQuery1 = KeywordsAnalysis::when(is_numeric($time), fn($query)=>$query->where('deadline','<=', $time))
            ->where('keywords', '<>', '')
            ->field(['keywords', 'max( deadline )' => 'deadline'])
            ->group('keywords')
            ->buildSql();
        $tableName = KeywordsAnalysis::getTable();
        $subQuery = KeywordsAnalysis::rightJoin('(' . $subQuery1 . ') t', "$tableName.keywords=t.keywords and $tableName.deadline=t.deadline")
            ->tableField(true, $tableName)
            ->buildSql();

        $tableName = Keywords::getTable();
        $query = Keywords::rightJoin('(' . $subQuery . ') ka', "$tableName.keywords=ka.keywords")
            ->search("$tableName.keywords", $kw)
            ->tableField(true, $tableName)
            ->tableField(['keywordsNum', 'titleNum', 'readNum', 'deadline',], 'ka')
            ->order('ka.readNum', 'DESC')
            ->order('ka.titleNum', 'DESC')
            ->order('ka.keywordsNum', 'DESC')
            ->order("$tableName.id", 'DESC')
            ->paging($page, $page_size);

        return listOutput($query, $page_size);
    }
}
